class FireworksShow {
    constructor() {
        this.canvas = document.getElementById('fireworksCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.starCanvas = document.getElementById('starCanvas');
        this.starCtx = this.starCanvas.getContext('2d');
        
        this.fireworks = [];
        this.particles = [];
        this.stars = [];
        
        this.settings = {
            type: 'classic',
            colorTheme: 'rainbow',
            launchSpeed: 5,
            particleDensity: 200,
            soundEnabled: true,
            autoMode: true,
            ecoMode: false
        };
        
        this.isMouseDown = false;
        this.lastLaunchTime = 0;
        this.autoLaunchInterval = null;
        
        this.init();
    }
    
    init() {
        this.setupCanvas();
        this.createStars();
        this.setupEventListeners();
        this.checkFestival();
        this.animate();
        
        if (this.settings.autoMode) {
            this.startAutoShow();
        }
    }
    
    setupCanvas() {
        const resizeCanvas = () => {
            this.canvas.width = window.innerWidth;
            this.canvas.height = window.innerHeight;
            this.starCanvas.width = window.innerWidth;
            this.starCanvas.height = window.innerHeight;
        };
        
        resizeCanvas();
        window.addEventListener('resize', resizeCanvas);
    }
    
    createStars() {
        const starCount = Math.floor((this.canvas.width * this.canvas.height) / 1000);
        
        for (let i = 0; i < starCount; i++) {
            this.stars.push({
                x: Math.random() * this.canvas.width,
                y: Math.random() * this.canvas.height,
                size: Math.random() * 2,
                opacity: Math.random(),
                speed: Math.random() * 0.05
            });
        }
    }
    
    setupEventListeners() {
        // 鼠标事件
        this.canvas.addEventListener('mousedown', (e) => {
            this.isMouseDown = true;
            this.launchFirework(e.clientX, e.clientY);
        });
        
        this.canvas.addEventListener('mousemove', (e) => {
            if (this.isMouseDown) {
                const now = Date.now();
                if (now - this.lastLaunchTime > 100) {
                    this.launchFirework(e.clientX, e.clientY);
                    this.lastLaunchTime = now;
                }
            }
        });
        
        this.canvas.addEventListener('mouseup', () => {
            this.isMouseDown = false;
        });
        
        // 触摸事件
        this.canvas.addEventListener('touchstart', (e) => {
            e.preventDefault();
            this.isMouseDown = true;
            const touch = e.touches[0];
            this.launchFirework(touch.clientX, touch.clientY);
        });
        
        this.canvas.addEventListener('touchmove', (e) => {
            e.preventDefault();
            if (this.isMouseDown) {
                const now = Date.now();
                if (now - this.lastLaunchTime > 100) {
                    const touch = e.touches[0];
                    this.launchFirework(touch.clientX, touch.clientY);
                    this.lastLaunchTime = now;
                }
            }
        });
        
        this.canvas.addEventListener('touchend', (e) => {
            e.preventDefault();
            this.isMouseDown = false;
        });
        
        // 控制面板事件
        document.getElementById('settings-btn').addEventListener('click', () => {
            document.getElementById('control-panel').classList.toggle('hidden');
        });
        
        document.getElementById('close-panel').addEventListener('click', () => {
            document.getElementById('control-panel').classList.add('hidden');
        });
        
        document.getElementById('fullscreen-btn').addEventListener('click', () => {
            if (!document.fullscreenElement) {
                document.documentElement.requestFullscreen();
            } else {
                document.exitFullscreen();
            }
        });
        
        // 设置变更
        document.getElementById('firework-type').addEventListener('change', (e) => {
            this.settings.type = e.target.value;
        });
        
        document.getElementById('color-theme').addEventListener('change', (e) => {
            this.settings.colorTheme = e.target.value;
        });
        
        document.getElementById('launch-speed').addEventListener('input', (e) => {
            this.settings.launchSpeed = parseInt(e.target.value);
            document.getElementById('speed-value').textContent = e.target.value;
        });
        
        document.getElementById('particle-density').addEventListener('input', (e) => {
            this.settings.particleDensity = parseInt(e.target.value);
            document.getElementById('density-value').textContent = e.target.value;
        });
        
        document.getElementById('sound-toggle').addEventListener('change', (e) => {
            this.settings.soundEnabled = e.target.checked;
        });
        
        document.getElementById('auto-mode').addEventListener('change', (e) => {
            this.settings.autoMode = e.target.checked;
            if (this.settings.autoMode) {
                this.startAutoShow();
            } else {
                this.stopAutoShow();
            }
        });
        
        document.getElementById('eco-mode').addEventListener('change', (e) => {
            this.settings.ecoMode = e.target.checked;
            document.body.classList.toggle('eco-mode', this.settings.ecoMode);
        });
    }
    
    getColorPalette() {
        const palettes = {
            rainbow: ['#FF0000', '#FF7F00', '#FFFF00', '#00FF00', '#0000FF', '#4B0082', '#9400D3'],
            'red-gold': ['#FF0000', '#FFD700', '#FF6347', '#FFA500'],
            'blue-purple': ['#0000FF', '#4B0082', '#9400D3', '#8A2BE2', '#4169E1'],
            random: null
        };
        
        return palettes[this.settings.colorTheme];
    }
    
    getRandomColor() {
        const palette = this.getColorPalette();
        if (palette) {
            return palette[Math.floor(Math.random() * palette.length)];
        }
        return `hsl(${Math.random() * 360}, 100%, 50%)`;
    }
    
    launchFirework(x, y) {
        const startX = x + (Math.random() - 0.5) * 100;
        const startY = this.canvas.height;
        const targetY = y * 0.7;
        
        const firework = {
            x: startX,
            y: startY,
            targetY: targetY,
            speed: this.settings.launchSpeed + Math.random() * 3,
            color: this.getRandomColor(),
            type: this.settings.type,
            exploded: false
        };
        
        this.fireworks.push(firework);
        
        if (this.settings.soundEnabled) {
            this.playSound();
        }
    }
    
    playSound() {
        const sound = document.getElementById('firework-sound');
        if (sound) {
            sound.currentTime = 0;
            sound.play().catch(() => {});
        }
    }
    
    startAutoShow() {
        this.autoLaunchInterval = setInterval(() => {
            const x = Math.random() * this.canvas.width;
            const y = Math.random() * this.canvas.height * 0.5;
            this.launchFirework(x, y);
        }, 2000);
    }
    
    stopAutoShow() {
        if (this.autoLaunchInterval) {
            clearInterval(this.autoLaunchInterval);
            this.autoLaunchInterval = null;
        }
    }
    
    createParticles(x, y, color, type) {
        const particleCount = this.settings.ecoMode ? 
            this.settings.particleDensity / 2 : 
            this.settings.particleDensity;
        
        for (let i = 0; i < particleCount; i++) {
            let angle, speed, size;
            
            switch (type) {
                case 'heart':
                    const t = (i / particleCount) * Math.PI * 2;
                    angle = t;
                    speed = 2 + Math.sin(t * 3) * 2;
                    break;
                case 'spiral':
                    angle = (i / particleCount) * Math.PI * 4;
                    speed = 1 + (i / particleCount) * 3;
                    break;
                case 'chrysanthemum':
                    angle = (i / particleCount) * Math.PI * 2;
                    speed = 2 + Math.sin(angle * 8) * 1.5;
                    break;
                case 'smiley':
                    if (i < particleCount / 3) {
                        angle = (i / (particleCount / 3)) * Math.PI;
                        speed = 2;
                    } else {
                        angle = Math.random() * Math.PI * 2;
                        speed = 1 + Math.random() * 3;
                    }
                    break;
                default: // classic
                    angle = (i / particleCount) * Math.PI * 2;
                    speed = 1 + Math.random() * 3;
            }
            
            size = this.settings.ecoMode ? 
                Math.random() * 2 + 1 : 
                Math.random() * 3 + 2;
            
            this.particles.push({
                x: x,
                y: y,
                vx: Math.cos(angle) * speed,
                vy: Math.sin(angle) * speed,
                color: color,
                size: size,
                life: 1,
                decay: 0.01 + Math.random() * 0.02
            });
        }
    }
    
    checkFestival() {
        const today = new Date();
        const month = today.getMonth() + 1;
        const day = today.getDate();
        
        let greeting = '';
        let theme = '';
        
        // 春节（农历新年，这里简化为1月21日-2月20日）
        if ((month === 1 && day >= 21) || (month === 2 && day <= 20)) {
            greeting = '新春快乐！';
            theme = 'red-gold';
        }
        // 元旦
        else if (month === 1 && day === 1) {
            greeting = '元旦快乐！';
            theme = 'rainbow';
        }
        // 国庆节
        else if (month === 10 && (day >= 1 && day <= 7)) {
            greeting = '国庆快乐！';
            theme = 'red-gold';
        }
        
        if (greeting) {
            this.showGreeting(greeting);
            if (theme) {
                this.settings.colorTheme = theme;
                document.getElementById('color-theme').value = theme;
            }
        }
    }
    
    showGreeting(text) {
        const greeting = document.getElementById('festival-greeting');
        const textElement = greeting.querySelector('.greeting-text');
        textElement.textContent = text;
        greeting.classList.remove('hidden');
        
        setTimeout(() => {
            greeting.classList.add('hidden');
        }, 3000);
    }
    
    update() {
        // 更新烟花
        for (let i = this.fireworks.length - 1; i >= 0; i--) {
            const firework = this.fireworks[i];
            
            if (!firework.exploded) {
                firework.y -= firework.speed;
                
                if (firework.y <= firework.targetY) {
                    firework.exploded = true;
                    this.createParticles(firework.x, firework.y, firework.color, firework.type);
                    this.fireworks.splice(i, 1);
                }
            }
        }
        
        // 更新粒子
        for (let i = this.particles.length - 1; i >= 0; i--) {
            const particle = this.particles[i];
            
            particle.x += particle.vx;
            particle.y += particle.vy;
            particle.vy += 0.1; // 重力
            particle.life -= particle.decay;
            
            if (particle.life <= 0) {
                this.particles.splice(i, 1);
            }
        }
        
        // 更新星星
        this.stars.forEach(star => {
            star.opacity += star.speed;
            if (star.opacity > 1 || star.opacity < 0.3) {
                star.speed = -star.speed;
            }
        });
    }
    
    draw() {
        // 清空画布
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制星星
        this.starCtx.clearRect(0, 0, this.starCanvas.width, this.starCanvas.height);
        this.stars.forEach(star => {
            this.starCtx.fillStyle = `rgba(255, 255, 255, ${star.opacity})`;
            this.starCtx.beginPath();
            this.starCtx.arc(star.x, star.y, star.size, 0, Math.PI * 2);
            this.starCtx.fill();
        });
        
        // 绘制烟花
        this.fireworks.forEach(firework => {
            if (!firework.exploded) {
                this.ctx.fillStyle = firework.color;
                this.ctx.beginPath();
                this.ctx.arc(firework.x, firework.y, 3, 0, Math.PI * 2);
                this.ctx.fill();
                
                // 拖尾效果
                this.ctx.fillStyle = `rgba(255, 255, 255, 0.5)`;
                this.ctx.beginPath();
                this.ctx.arc(firework.x, firework.y + 5, 1, 0, Math.PI * 2);
                this.ctx.fill();
            }
        });
        
        // 绘制粒子
        this.particles.forEach(particle => {
            this.ctx.save();
            this.ctx.globalAlpha = particle.life;
            this.ctx.fillStyle = particle.color;
            this.ctx.beginPath();
            this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
            this.ctx.fill();
            
            // 发光效果
            this.ctx.shadowColor = particle.color;
            this.ctx.shadowBlur = 10;
            this.ctx.fill();
            this.ctx.restore();
        });
    }
    
    animate() {
        this.update();
        this.draw();
        requestAnimationFrame(() => this.animate());
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    new FireworksShow();
});
